# ~*~ coding: utf-8 ~*~
import time

from apps.common.dbbase import BaseModel
from apps.common.utils import generate_uuid
from apps.extensions import db
from sqlalchemy.dialects.mysql import TINYINT

__all__ = ['Task']


class Task(BaseModel):
    __tablename__ = 'codes_task'

    # 上线状态：0新建提交-待审核，1审核通过-待上线，2审核拒绝，3正在上线，4上线完成，5上线失败，6、已回滚
    # 回滚状态：0新建提交-待回滚，                         3正在回滚，4回滚完成，5回滚失败
    STATUS_NEW = 0
    STATUS_APPROVAL = 1
    STATUS_REJECT = 2
    STATUS_DOING = 3
    STATUS_SUCCESS = 4
    STATUS_FAIL = 5
    STATUS_ROLLBACK = 6

    # 回滚/上线
    ACTION_DEPLOY = 1
    ACTION_ROLLBACK = 2

    id = db.Column(db.CHAR(36), default=generate_uuid, primary_key=True)
    # 上线标题
    title = db.Column(db.VARCHAR(255))
    # 上线内容
    content = db.Column(db.TEXT)
    # 用户ID
    user_id = db.Column(db.CHAR(36))
    # 项目ID
    project_id = db.Column(db.CHAR(36))
    # 上线类型
    action = db.Column(TINYINT, default=ACTION_DEPLOY)
    # 工单状态
    status = db.Column(TINYINT, default=STATUS_NEW)
    # 本次link_id
    link_id = db.Column(db.VARCHAR(128), default='')
    # 上次link_id
    pre_link_id = db.Column(db.VARCHAR(128), default='')

    # 版本号
    commit = db.Column(db.String(64), default='')
    # branch版本号
    branch = db.Column(db.String(64), default='')
    # tag版本号
    tag = db.Column(db.String(64), default='')

    # 审批人
    approval_user = db.Column(db.VARCHAR(32), nullable=True)

    create_by = db.Column(db.VARCHAR(32), nullable=True)
    create_time = db.Column(db.INT, default=time.time)
    update_time = db.Column(db.INT, default=time.time, onupdate=time.time)

    @property
    def short_id(self):
        return str(self.id).split('-')[-1]

    @property
    def is_deploy(self):
        # 可以上线的状态：1, 5
        if self.action == Task.ACTION_DEPLOY:
            return self.status == Task.STATUS_APPROVAL or self.status == Task.STATUS_FAIL

    @property
    def is_rollback(self):
        # 可以回滚的状态：4
        if self.action == Task.ACTION_DEPLOY:
            return self.status == Task.STATUS_SUCCESS

    def __str__(self):
        return '<Task: {}>'.format(self.title)
